package com.project.application.framework.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.application.common.exception.ServiceException;
import com.project.application.common.utils.SecurityUtils;
import com.project.application.framework.security.RegisterBody;
import com.project.application.server.system.domain.SysUser;
import com.project.application.server.system.service.CaptchaService;
import com.project.application.server.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 注册校验方法
 *
 * @author levnli
 */
@Component
public class SysRegisterService {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private CaptchaService captchaService;

    /**
     * 注册
     * @param registerBody 注册信息
     * @return 结果
     */
    public boolean register(RegisterBody registerBody) {
        captchaService.validateCaptcha(registerBody.getCode(), registerBody.getUuid());
        long count = userService.count(new QueryWrapper<>(new SysUser().setUserName(registerBody.getUsername())));
        if (count > 0) {
            throw new ServiceException("用户已存在");
        }
        if (!registerBody.getPassword().equals(registerBody.getRepPassword())) {
            throw new ServiceException("两次密码不一致");
        }
        SysUser user = new SysUser();
        user.setUserName(registerBody.getUsername())
            .setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()))
            .setStatus("0");
        return userService.save(user);
    }
}
